package com.cloudfast.platform.role.service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloudfast.common.page.Page;
import com.cloudfast.common.user.UserUtils;
import com.cloudfast.platform.role.dao.RoleDao;
import com.cloudfast.platform.role.dao.RoleMenuDao;
import com.cloudfast.platform.role.entity.Role;
import com.cloudfast.platform.role.entity.RoleMenu;
import com.cloudfast.platform.user.dao.UserRoleDao;

/**
 * @author liuyw
 * @描述:角色service
 * @date 2020年4月10日
 */
@Service
@Transactional(readOnly = true)
public class RoleService {

    protected static final Logger logger = LoggerFactory.getLogger(Logger.class);

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RoleMenuDao roleMenuDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Transactional(readOnly = false)
    public void clearUserRoleByUserId(Long userId) {
        this.userRoleDao.clearUserRole(userId);
    }

    /**
     * 保存 角色和 菜单的管理
     *
     * @param roleMenu
     */
    @Transactional(readOnly = false)
    public void saveRoleMenu(RoleMenu roleMenu) {
        roleMenuDao.save(roleMenu);
    }

    /**
     * 清空 角色关联的 菜单
     *
     * @param roleId
     */
    public void clearRoleMenuByRoleId(Long roleId) {
        StringBuilder deleteRoleMenu = new StringBuilder("delete from RoleMenu where roleId=:roleId ");
        Map<String, Object> params = new HashMap<>();
        params.put("roleId", roleId);
        roleMenuDao.excute(deleteRoleMenu.toString(), params);
    }

    /**
     * @param id
     * @param code
     * @return @
     * @描述:
     * @author liuyw
     * @date 2020年4月20日
     */
    public int checkCode(Long id, String code) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("code", code);
        StringBuilder sql = new StringBuilder("from Role where 1=1 and code=:code");
        if (id != null && id > 0) {
            sql.append(" and id!=:id");
            params.put("id", id);
        }
        List<Role> list = roleDao.findList(sql.toString(), params);
        if (list != null && !list.isEmpty()) {
            return list.size();
        }
        return 0;
    }

    /**
     * @param entity
     * @描述: 保存
     * @author liuyw
     * @date 2020年4月10日
     */
    @Transactional(readOnly = false)
    public void save(Role entity) {
        try {
            roleDao.saveOrUpdate(entity);
            // 关联菜单
            String[] menus = entity.getMenus().split(",");
            clearRoleMenuByRoleId(entity.getId());
            for (int i = 0; i < menus.length; i++) {
                if (StringUtils.isNotEmpty(menus[i])) {
                    Long menuId = Long.valueOf(menus[i]);
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMenuId(menuId);
                    roleMenu.setRoleId(entity.getId());
                    roleMenu.setId(entity.getId() + "_" + menuId);
                    saveRoleMenu(roleMenu);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Transactional(readOnly = false)
    public void delete(Long id) {
        clearRoleMenuByRoleId(id);
        this.roleDao.deleteById(id);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param entity
     * @return
     */
    public Page<Role> findPage(Page<Role> page, Role entity) {
        Map<String, Object> params = new HashMap<>();

        StringBuffer ql = new StringBuffer(" from Role where 1=1 ");
        if (StringUtils.isNotEmpty(entity.getName())) {
            ql.append(" and name=:name ");
            params.put("name",entity.getName());
        }
        if (StringUtils.isNotEmpty(entity.getCode())) {
            ql.append(" and code=:code ");
            params.put("code",entity.getCode());

        }
        if (StringUtils.isNotEmpty(entity.getDelFlag())) {
            ql.append(" and delFlag=:delFlag ");
            params.put("delFlag",entity.getDelFlag());
        }else{
            ql.append(" and delFlag='0' ");
        }
        if (!UserUtils.hasPermission("super_admin")) {
            ql.append(" and isAdmin != :isAdmin ");
            params.put("isAdmin", "super");
        }
        return this.roleDao.findPage(page, ql.toString(),params);
    }

    public List<Role> findList(Role entity) {
        Map<String, Object> params = new HashMap<>();
        StringBuilder hql = new StringBuilder("from Role where 1=1 and delFlag='0' ");
        if (!UserUtils.hasPermission("super_admin")) {
            hql.append(" and isAdmin != :isAdmin ");
            params.put("isAdmin", "super");
        }
        return this.roleDao.findList(hql.toString(), params);
    }

    /**
     * 角色下是否关联用户
     * @param roleId
     * @return
     */
    public boolean hasUser(Long roleId){
        Map<String, Object> _params = new LinkedHashMap<>();
        _params.put("roleId",roleId);
        StringBuilder sql=new StringBuilder("select * from sys_user_role where 1=1  and role_id=:roleId");
        List<Map<String, Object>> list=roleDao.nativeQuery(sql.toString(), _params);
        return list!=null&&list.size()>0;
    }
    /**
     * 保存角色用户信息
     *
     * @param roleId
     * @param userId
     */
    @Transactional(readOnly = false)
    public void addUser(Long roleId, Long userId) {
        try {
            Map<String, Object> _params = new LinkedHashMap<>();

            _params.put("id", roleId + "_" + userId);
            _params.put("userId", userId);
            _params.put("roleId", roleId);

            StringBuffer ql = new StringBuffer(
                    "INSERT INTO sys_user_role(id,user_id, role_id) VALUES (:id,:userId, :roleId);");
            roleDao.nativeExcute(ql.toString(), _params);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 删除角色用户信息
     *
     * @param roleId
     * @param userId
     */
    @Transactional(readOnly = false)
    public void moveUser(Long roleId, Long userId) {
        Map<String, Object> _params = new LinkedHashMap<>();
        _params.put("userId", userId);
        _params.put("roleId", roleId);
        StringBuffer ql = new StringBuffer("delete from sys_user_role where user_id=? and role_id=?;");
        roleDao.nativeExcute(ql.toString(), _params);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public Role findOne(Long id) {
        return this.roleDao.findOne(id);
    }

    /**
     * 根据userid 查询 角色 信息
     *
     * @param userId
     * @return
     */
    public List<Role> findRoleByUserId(Long userId) {
        StringBuilder hql = new StringBuilder(
                "select role from Role role,UserRole userRole where userRole.roleId=role.id ");
        hql.append(" and userRole.userId=:userId");
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        return this.roleDao.findList(hql.toString(), params);
    }

}
